//
//  recommendInterfaceViewController.m
//  INAlienLand
//
//  Created by dllo on 15/6/29.
//  Copyright (c) 2015年 dllo. All rights reserved.
//
#define WIDTH self.view.frame.size.width
#define HIGHT self.view.frame.size.height
#import "recommendInterfaceViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "RecommendCell.h"
#import "ScrollerModel.h"
#import "TypeWith4Model.h"
#import "SecondWebViewController.h"
#import "MJRefresh.h"
#import "HTTPTool.h"
#import "MyCollectionViewCell.h"
#import "MBProgressHUD.h"
@interface recommendInterfaceViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,retain)UITableView *tableview;
@property(nonatomic,retain)UIScrollView *scrollerview;
@property(nonatomic,retain)NSMutableArray *searchArr;
@property(nonatomic,retain)NSMutableArray *elementArr;
@property(nonatomic,retain)NSMutableArray *scrollArr;
@property(nonatomic,retain)UIImageView *imageview;
@property(nonatomic,retain)NSMutableArray *AllTypeArr;
@property(nonatomic,retain)NSMutableArray *typeArr;
@property(nonatomic,retain)UIView *HeaderView;
@property(nonatomic,assign)NSInteger count;
@property(nonatomic,retain)NSMutableArray *NextStartArr;
@property(nonatomic,copy)NSString *NextUrl;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,retain)UICollectionView *collection;
@property(nonatomic,retain)NSString *nextstr;
@property(nonatomic,retain)NSMutableArray *topArr;

@property(nonatomic,retain)MBProgressHUD *hud;
@end


@implementation recommendInterfaceViewController

- (void)dealloc{
    [self.topArr release];
    [self.tableview release];
    [self.scrollArr release];
    [self.imageview release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //创建tableview
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64-49) style:UITableViewStylePlain];
    self.tableview.backgroundColor = [UIColor colorWithWhite:0.896 alpha:1.000];
    [self.view addSubview:self.tableview];
    
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    //tableview的高
    self.tableview.rowHeight = self.view.frame.size.height/3;
    //去掉分割线
    self.tableview.separatorStyle = UITableViewCellSelectionStyleNone;
    self.HeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/3)];
    self.tableview.tableHeaderView = self.HeaderView;
    
    [self.tableview release];
    self.scrollArr = [NSMutableArray array];
    self.typeArr = [NSMutableArray array];
    self.elementArr = [NSMutableArray array];
    self.searchArr = [NSMutableArray array];
    self.AllTypeArr = [NSMutableArray array];
    self.NextStartArr = [NSMutableArray array];
    self.topArr = [NSMutableArray array];
    
    [self AFN];
    [self scroll];
    [self.tableview reloadData];
    
    self.title =  @"推荐";
    //上拉加载
    
    
    [self.tableview addFooterWithCallback:^{
        
        [self AFN];
        [self.tableview footerEndRefreshing];
    }];
    //下拉刷新
    [self.tableview addHeaderWithCallback:^{
        [self AFN];
        [self.tableview headerEndRefreshing];
    }];
    //加载小菊花
    self.hud = [MBProgressHUD showHUDAddedTo:self.tableview animated:YES];
    [self.hud setDimBackground:YES];
    self.hud.labelText = @"加载...";
    [self.hud show:YES];
}


- (void)scroll{
    
    UICollectionViewFlowLayout *flawout = [[UICollectionViewFlowLayout alloc]init];
    
    flawout.itemSize = CGSizeMake(self.HeaderView.frame.size.width, self.view.frame.size.height/3);
    //设置滑动方向
    flawout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //去掉列间距
    flawout.minimumLineSpacing = 0;
    flawout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.HeaderView.frame.size.width, self.view.frame.size.height/3) collectionViewLayout:flawout];
    self.collection.dataSource = self;
    self.collection.delegate = self;
    [self.HeaderView addSubview: self.collection];
    self.collection.backgroundColor = [UIColor whiteColor];
    [ self.collection registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.collection.pagingEnabled = YES;
    
    
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeimage) userInfo:nil repeats:YES];
    
    
    
    
    
    
}

- (void)changeimage{
    [self.collection setContentOffset:CGPointMake(self.collection.contentOffset.x+self.HeaderView.frame.size.width, 0) animated:YES];
    if (self.collection.contentOffset.x == self.HeaderView.frame.size.width*(self.scrollArr.count-1)) {
        self.collection.contentOffset = CGPointMake(self.HeaderView.frame.size.width, 0);
        
    }
    else if (self.collection.contentOffset.x == 0){
        self.collection.contentOffset = CGPointMake(self.HeaderView.frame.size.width*(self.scrollArr.count-2), 0);
    }
    
}





- (void)AFN{

    
 
    if ( self.nextstr==nil) {
        
     
        
        [HTTPTool get:@"http://api.breadtrip.com/v5/index/?is_ipad=0&sign=c421d0f26bbfc52e0bcae33ca2cdedb5" body:nil HTTPResult:JSON success:^(id result) {
            
            //移除小菊花
          
            [self.hud hide:YES];
            
            self.scrollArr = [NSMutableArray array];
            
            NSDictionary *dic = [[NSDictionary alloc]init];
            dic = result;
            
            self.searchArr  = dic[@"search_data"];
            self.elementArr = dic[@"elements"];
            self.nextstr = dic[@"next_start"];
            
            [self.NextStartArr addObject:self.nextstr];
            
            for (NSMutableDictionary *tempDic in self.elementArr) {
                
                ScrollerModel *scroll = [[ScrollerModel alloc]init];
                [scroll setValuesForKeysWithDictionary:tempDic];
                [self.typeArr addObject:scroll];
                
                if ([scroll.desc isEqualToString:@"广告banner"]) {
                    
                    
                    NSArray *inDataArr = [scroll.data lastObject];
                    
                    [self.scrollArr addObject:inDataArr[inDataArr.count-1][@"image_url"]];
                    [self.topArr addObject:inDataArr[inDataArr.count-1][@"html_url"]];
                    
                    for (NSInteger i = 0; i<inDataArr.count; i++) {
                        
                        [self.scrollArr addObject:inDataArr[i][@"image_url"]];
                        
                        [self.topArr addObject:inDataArr[i][@"html_url"]];
                        
                    }
                    
                    [self.topArr addObject:inDataArr[0][@"html_url"]];
                    [self.scrollArr addObject:inDataArr[0][@"image_url"]];
                    //
                    //                    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES);
                    //                    NSString *sandBoxPath =sandBox[0];
                    //                    //向这个路径里拼接一个plist文件
                    //                    NSString *documenttop = [sandBoxPath stringByAppendingPathComponent:@"CollectionView.plist"];
                    //                    //归档操作
                    //                   [NSKeyedArchiver archiveRootObject:self.scrollArr toFile:documenttop];
                    //
                    
                    
                    
                    
                }else if([scroll.desc isEqualToString:@"热门游记"]||[scroll.desc isEqualToString:@"一个专题"]||[scroll.desc isEqualToString:@"推荐旅行产品"]){
                    
                    for (NSDictionary *tempdic in scroll.data) {
                        TypeWith4Model *type = [[TypeWith4Model alloc]init];
                        [type setValuesForKeysWithDictionary:tempdic];
                        [self.AllTypeArr addObject:type];
                        [type release];
                    }
                    
                }
                ////
                //                NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES);
                //                NSString *sandBoxPath =sandBox[0];
                //                //向这个路径里拼接一个plist文件
                //                NSString *documentAll = [sandBoxPath stringByAppendingPathComponent:@"Tableview.plist"];
                //                //归档操作
                //                [NSKeyedArchiver archiveRootObject:self.AllTypeArr toFile:documentAll];
                ////
                [self.collection reloadData];
                [self.tableview reloadData];
            }
            
            
            
            NSLog(@"%ld",self.NextStartArr.count);
            
        } failure:^(NSError *error) {
            
            //  [self.hud removeFromSuperview];
            UIAlertView *alret = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络异常,请检查网络连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alret show];
            NSLog(@"123");
        }];
    }else{
        // NSLog(@"%ld",self.NextStartArr.count);
        for (NSInteger i = 0; i<self.NextStartArr.count; i++) {
            
            self.NextUrl = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88287764798017&lng=121.5398279985663&next_start=%@&sign=7d877a460e9b51fa552a74de7cdffe10",self.NextStartArr[i]];
        }
        // NSLog(@"%@",self.NextStartArr[page]);
        [HTTPTool get:self.NextUrl body:nil HTTPResult:JSON success:^(id result) {
            
            NSDictionary *dic = [[NSDictionary alloc]init];
            dic = result;
            NSMutableArray *element = dic[@"elements"];
            NSString *next = dic[@"next_start"];
            [self.NextStartArr addObject:next];
            for (NSMutableDictionary *tempdic in element) {
                
                ScrollerModel *scroll = [[ScrollerModel alloc]init];
                [scroll setValuesForKeysWithDictionary:tempdic];
                [self.typeArr addObject:scroll];
                
                for (NSDictionary *tempdic in scroll.data) {
                    TypeWith4Model *type = [[TypeWith4Model alloc]init];
                    [type setValuesForKeysWithDictionary:tempdic];
                    [self.AllTypeArr addObject:type];
                    [type release];
                }
                
            }
            
            
            [self.tableview reloadData];
            
            
            
            
            
        } failure:^(NSError *error) {
            
            
        }];
        
    }
    
    
    [self.tableview reloadData];
    
}

//- (void)caches{
//
//
//        NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES);
//        NSString *sandBoxPath = sandBox[0];
//        NSString *docmentTop = [sandBoxPath stringByAppendingPathComponent:@"CollectionView.plist"];
//        self.scrollArr = [NSKeyedUnarchiver unarchiveObjectWithFile:docmentTop];
//        NSLog(@"%@",docmentTop);
//
//    NSString *docmenttableview = [sandBoxPath stringByAppendingPathComponent:@"Tableview.plist"];
//    self.scrollArr = [NSKeyedUnarchiver unarchiveObjectWithFile:docmenttableview];
//    NSLog(@"%@",docmenttableview);
//    [self.tableview reloadData];
//}


//collectionview点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    SecondWebViewController *second = [[SecondWebViewController alloc]init];
    second.Url = self.topArr[indexPath.row];
    [self.navigationController pushViewController:second animated:YES];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    // NSLog(@"123");
    // NSLog(@"%ld",self.scrollArr.count);
    return self.scrollArr.count;
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    [cell.imageview sd_setImageWithURL:[NSURL URLWithString:self.scrollArr[indexPath.row]]];
    
    
    
    return cell;
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // NSLog(@"%ld",self.AllTypeArr.count);
    return self.AllTypeArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    ScrollerModel *scroll = self.typeArr[indexPath.row+1];
    TypeWith4Model *type = self.AllTypeArr[indexPath.row];
    
    
    
    static NSString *reuse = @"reuse";
    RecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        
        cell = [[[RecommendCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    for (NSInteger i = 1; i<self.AllTypeArr.count+1; i++) {
        
        
        
        if (type.cover_image) {
            
            [cell.imageview sd_setImageWithURL:[NSURL URLWithString:type.cover_image]];
            
            
        }else{
            
            [cell.imageview sd_setImageWithURL:[NSURL URLWithString:type.cover]];
            
        }
        
        
        
        switch (scroll.type) {
            case 4:
                cell.titlelabel.text = type.name;
                cell.Firstdaylabel.text = type.first_day;
                cell.Placename.text = type.popular_place_str;
                break;
                
            default:
                cell.titlelabel.text = type.name;
                cell.Firstdaylabel.text = type.first_day;
                cell.Placename.text = type.popular_place_str;
                break;
        }
        
        
        switch (scroll.type) {
            case 5:
                cell.type5tittle.text = type.cover_sub_title;
                break;
                
            default:
                cell.type5tittle.text = type.cover_sub_title;
                cell.Midtitlelabel.text = type.cover_title;
                break;
        }
        
        switch (scroll.type) {
            case 7:
                
                break;
                
            default:
                
                cell.Midlittle.text = type.title;
                cell.Midtitlelabel.text = type.cover_title;
                cell.MidSubtittle.text = type.sub_title;
                break;
        }
        
        
        
   }
//    
    
    
    if (cell.titlelabel.text.length>self.imageview.frame.size.width-40) {
        cell.titlelabel.numberOfLines = 2;
    }
    
    
    return cell;
    
    
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SecondWebViewController *second = [[SecondWebViewController alloc]init];
    [self.navigationController pushViewController:second animated:YES];
    ScrollerModel *scroll = self.typeArr[indexPath.row+1];
    TypeWith4Model *type = self.AllTypeArr[indexPath.row];
    
    for (NSInteger i = 1; i<self.AllTypeArr.count+1; i++) {
        
        
        if (type.cover_image) {
            
            second.Url = [NSString stringWithFormat:@"http://breadtrip.com/trips/%@/",type.bId];
            second.name = type.name;
        }else{
            
            
            second.Url = type.url;
            
            if ((scroll.type)==7) {
                second.name = type.sub_title;
                break;
            }else{
                second.name = type.cover_title;
                break;
            }
            
        }
        
    }
    
    
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
